package org.example.Handler;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.example.Command.FileMessage;
import org.example.Poll;

import java.io.File;
import java.io.RandomAccessFile;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

import static org.example.Constant.fileDirectory;
import static org.example.Utils.StringUtils.getRandomString;

public class SendCommandServerHandler extends SimpleChannelInboundHandler<FileMessage> implements SaveFile {
    private String key;
    private Path p;

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, FileMessage msg) throws Exception {
        if (Poll.sequenceId2Key.get(msg.getSequenceId()) == null) {
            //创建暂存标志
            String randomString = getRandomString(10);
            Poll.sequenceId2Key.put(msg.getSequenceId(), randomString);
            key = randomString;
        }

        //尝试创建目录
        if(!Files.exists(Paths.get(fileDirectory + File.separator + key))){
            p = Files.createDirectory(Paths.get(fileDirectory + File.separator + key));
        }
        //保存文件
        SaveFile.saveFile(msg,p.toFile());
    }
}
